45I - TCMCF+++ - CodeForces Solution


greedy *1400

Please click on ads to support us..

Python Code:

import sys
from heapq import heappop, heappush

input = lambda: sys.stdin.readline().rstrip()
I = lambda: int(input())
MI = lambda: map(int, input().split())
GMI = lambda: map(lambda x: int(x) - 1, input().split())
LI = lambda: list(MI())
LGMI = lambda: list(GMI())
YN = lambda x: print('YES' if x else 'NO')
mod = 1000000007
mod2 = 998244353

n = I()
nums = LI()
h = []
rst = []
zero = 0
for x in nums:
    if x > 0:
        rst.append(x)
    elif x < 0:
        heappush(h, x)
    else:
        zero += 1
while len(h) >= 2:
    rst.append(heappop(h))
    rst.append(heappop(h))

if rst:
    print(*rst)
else:
    if zero:
        print(0)
    else:
        print(max(h))

C++ Code:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <string>
using namespace std;

void solve() {
    int n;
    cin >> n;

    vector<int> pos, z, neg;

    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;

        if (x > 0)
            pos.push_back(x);
        else if (x == 0)
            z.push_back(x);
        else
            neg.push_back(x);
    }

    sort(neg.begin(), neg.end());

    vector<int> res = pos;
    if (neg.size() > 1) {
        for (int i = 0; i + 1 < neg.size(); i += 2) {
            res.push_back(neg[i]);
            res.push_back(neg[i + 1]);
        }
    }

    if (res.empty() && !z.empty())
        res.push_back(z[0]);

    if (res.empty() && !neg.empty())
        res.push_back(neg[0]);

    for (int x : res)
        cout << x << " ";
}

int main() {
    int n = 1;
    //cin >> n;

    for (int i = 0; i < n; i++)
        solve();
}


Comments

Submit
0 Comments
More Questions

975C - Valhalla Siege
518B - Tanya and Postcard
514B - Han Solo and Lazer Gun
898B - Proper Nutrition
9C - Hexadecimal's Numbers
1265B - Beautiful Numbers
745A - Hongcow Learns the Cyclic Shift
873A - Chores
1754B - Kevin and Permutation
1547D - Co-growing Sequence
1754D - Factorial Divisibility
1117B - Emotes
412B - Network Configuration
845B - Luba And The Ticket
1732A - Bestie
389A - Fox and Number Game
1732B - Ugu
1100B - Build a Contest
1181B - Split a Number
1313B - Different Rules
1736D - Equal Binary Subsequences
1754A - Technical Support
26B - Regular Bracket Sequence
699A - Launch of Collider
474D - Flowers
1016A - Death Note
1335C - Two Teams Composing
1167C - News Distribution
813C - The Tag Game
1130C - Connect